package appbuilder.wizards.gui.data.model;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import appbuilder.wizards.gui.data.model.validator.DatabaseSettingsValidator;

import com.jgoodies.binding.PresentationModel;
import com.jgoodies.validation.ValidationResult;
import com.jgoodies.validation.ValidationResultModel;
import com.jgoodies.validation.util.DefaultValidationResultModel;

public class DatabaseSettingsModel extends PresentationModel<DatabaseSettings> {
	private static final long serialVersionUID = 6844631644835750782L;
	
	private final ValidationResultModel validationResultModel;
	
	public DatabaseSettingsModel(DatabaseSettings settings) {
		super(settings);
        validationResultModel = new DefaultValidationResultModel();
        initEventHandling();
        updateValidationResult();
	}
	
    public ValidationResultModel getValidationResultModel() {
        return validationResultModel;
    }

    /**
     * Listens to changes in all properties of the current DatabaseSettings.
     */
    private void initEventHandling() {
        PropertyChangeListener handler = new ValidationUpdateHandler();
        addBeanPropertyChangeListener(handler);
        getBeanChannel().addValueChangeListener(handler);
    }

    private void updateValidationResult() {
        DatabaseSettings settings = getBean();
        ValidationResult result = new DatabaseSettingsValidator().validate(settings);
        validationResultModel.setResult(result);
    }

    /**
     * Validates the order using an DatabaseSettingsValidator and
     * updates the validation result.
     */
    private final class ValidationUpdateHandler implements PropertyChangeListener {
        public void propertyChange(PropertyChangeEvent evt) {
            updateValidationResult();
        }
    }
}
